package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.alipay.AuthResult;
import com.zhongjian.technologycal.mall.alipay.PayResult;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.VipPayBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/25.
 * 实现现金币充值
 */

public class RechargeCashActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.rechage_et_money)
    EditText rechage_et_money;
    @BindView(R.id.rechage_tv_commit)
    TextView rechage_tv_commit;

    private int REQUEST_READ_PHONE_STATE = 1001;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(msg.obj.toString());
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUitl.showShort("支付成功");
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUitl.showShort("支付取消");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(RechargeCashActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                        ToastUitl.showShort("授权成功");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUitl.showShort("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


    @Override
    protected void beforeInit() {
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("现金币充值");

    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_recharge_cash;
    }

    @OnClick(R.id.rechage_tv_commit)
    public void onClickRechagemoney() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        } else {
            if(TextUtils.isEmpty(rechage_et_money.getText().toString())){
                ToastUitl.showShort("请输入充值金额～");
                return;
            }else if(Double.valueOf(rechage_et_money.getText().toString()) < 1){
                ToastUitl.showShort("充值金额不能小于1～");
                return;
            }else{
                HttpRetrofitClient.getInstance(getBaseContext())
                        .postUrlRequestOfShipMoney(UserUtils.getUserToken(),
                                Double.valueOf(rechage_et_money.getText().toString()),
                                new Subscriber<ResponseBody>() {
                                    @Override
                                    public void onStart() {
                                        super.onStart();
                                    }

                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(ResponseBody responseBody) {
                                        try {
                                            Gson gson = new Gson();
                                            VipPayBean vipPayBean = gson.fromJson(responseBody.string(),VipPayBean.class);
                                            if(vipPayBean.getError_code() == 0){
                                                final String payInfo = vipPayBean.getData();
                                                Runnable payRunnable = new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        // 构造PayTask 对象
                                                        PayTask alipay = new PayTask(
                                                                RechargeCashActivity.this);
                                                        // 调用支付接口，获取支付结果
                                                        String result = alipay.pay(payInfo, true);
                                                        Message msg = new Message();
                                                        msg.what = SDK_PAY_FLAG;
                                                        msg.obj = result;
                                                        mHandler.sendMessage(msg);
                                                    }
                                                };
                                                // 必须异步调用
                                                Thread payThread = new Thread(payRunnable);
                                                payThread.start();
                                            }else if(vipPayBean.getError_code() == 1) {
                                                ToastUitl.showShort(vipPayBean.getError_message());
                                            }else if(vipPayBean.getError_code() == 3){
                                                Intent intent = new Intent();
                                                intent.setAction("com.broadcast.info_out_line");
                                                sendBroadcast(intent);
                                            }else{
                                                ToastUitl.showShort(vipPayBean.getError_message());
                                            }
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }

                                    }
                                });
            }

        }


    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

}
